package network.tcp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

//服务器
public class TcpServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream stream = null;
        ByteArrayOutputStream byteOS = null;

        try {
            //1.服务端提供地址
            serverSocket = new ServerSocket(10011);

            //2.等待客户端连接
            socket = serverSocket.accept();

            //3.接受客户端消息 IO流
            stream = socket.getInputStream();
            //使用管道流，修正字符编码
            byteOS = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = stream.read(buffer))!=-1) {
                byteOS.write(buffer,0,len);
            }
            System.out.println(byteOS.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.关闭资源
            if (byteOS!=null) {
                try {
                    byteOS.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (stream!=null) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket!=null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
